package com.example.todosync.service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.*;

@Service
public class StorageService {
    private final ObjectMapper mapper = new ObjectMapper();
    private final Path baseDir = Paths.get(System.getProperty("user.dir"), "data");

    private Path fileForUser(String user) {
        return baseDir.resolve(user).resolve("todos.json");
    }

    public synchronized List<JsonNode> readItems(String user) {
        Path file = fileForUser(user);
        try {
            if (!Files.exists(file)) return Collections.emptyList();
            try (InputStream in = Files.newInputStream(file)) {
                JsonNode root = mapper.readTree(in);
                if (root.isArray()) {
                    return mapper.convertValue(root, new TypeReference<List<JsonNode>>() {});
                }
                JsonNode itemsNode = root.path("items");
                if (itemsNode.isArray()) {
                    return mapper.convertValue(itemsNode, new TypeReference<List<JsonNode>>() {});
                }
                return Collections.emptyList();
            }
        } catch (IOException e) {
            return Collections.emptyList();
        }
    }

    public synchronized void writeItems(String user, List<JsonNode> items) throws IOException {
        Path file = fileForUser(user);
        Files.createDirectories(file.getParent());
        Map<String, Object> payload = new HashMap<>();
        payload.put("version", 1);
        payload.put("exportedAt", System.currentTimeMillis());
        payload.put("items", items);
        try (OutputStream out = Files.newOutputStream(file, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) {
            mapper.writerWithDefaultPrettyPrinter().writeValue(out, payload);
        }
    }
}